package com.heima.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.Result;
import com.heima.context.ResidentContext;
import com.heima.domain.dto.PageDTO;
import com.heima.domain.po.MessageBoard;
import com.heima.domain.query.MessageBoardQuery;
import com.heima.exception.DIYException;
import com.heima.mapper.MessageBoardMapper;
import com.heima.service.IMessageBoardService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 在线留言表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-08-05
 */
@Service
public class MessageBoardServiceImpl extends ServiceImpl<MessageBoardMapper, MessageBoard> implements IMessageBoardService {
  @Autowired
    private MessageBoardMapper messageBoardMapper;
   public Result findByPage(MessageBoardQuery query){
       Integer pageNum = query.getPageNum();
         Integer pageSize = query.getPageSize();
       Page<MessageBoard> page = new Page<>(pageNum, pageSize);
       Page<MessageBoard> p = messageBoardMapper.findByPage(page, query);
       List<MessageBoard> records = p.getRecords();
       if (records.isEmpty()) { // 如果结果为空
           return Result
                   .success(new PageDTO<>(p.getTotal(), p.getSize(), p.getPages(), (long)pageNum, new ArrayList<>())); // 返回空数据的分页结果
       }
       return Result
               .success(new PageDTO<>(p.getTotal(), p.getSize(), p.getPages(), (long)pageSize, records)); // 返回查询到的数据分页结果
   }
   public  Result MyfindByPage(MessageBoardQuery query){
       if (ResidentContext.getCurrentId() == null) {
           throw new DIYException("请先登录");
       }
       Long userId = ResidentContext.getCurrentId();
       Integer pageNum = query.getPageNum();
       Integer pageSize = query.getPageSize();
       Page<MessageBoard> page = new Page<>(pageNum, pageSize);
       Page<MessageBoard> p = messageBoardMapper.MyfindByPage(page, query, userId);
       List<MessageBoard> records = p.getRecords();
       if (records.isEmpty()) { // 如果结果为空
           return Result
                   .success(new PageDTO<>(p.getTotal(), p.getSize(), p.getPages(), (long)pageNum, new ArrayList<>())); // 返回空数据的分页结果
       }
       return Result
               .success(new PageDTO<>(p.getTotal(), p.getSize(), p.getPages(), (long)pageSize, records)); // 返回查询到的数据分页结果

   }
   }

